#!/usr/bin/env groovy
// @file    ScanTool
// @author  Mac Radigan
// @version $Id$

package ycoa.scan.process

import sys.tools.Tool
import ycoa.scan.process.ScanClient
import ycoa.servlet.YCOAServletContainer
import ycoa.configuration.YCOAConfiguration

import ycoa.*
import ycoa.archive.*
import ycoa.session.*
import ycoa.service.*
import ycoa.markup.*
import ycoa.text.*
import ycoa.scan.process.*
import ycoa.scan.signin.*
import ycoa.graphics.*
import sys.utilities.ResourceManager

import java.awt.PopupMenu
import java.awt.Toolkit
import java.awt.SystemTray
import java.awt.Image
import java.awt.MenuItem
import java.awt.TrayIcon

import java.util.Timer
import java.util.TimerTask
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.Date
import org.apache.log4j.Logger

public class ScanTool extends Tool {

  static Logger log = Logger.getLogger(ScanSigninTool.class)

  public String getName() {
    return "scan"
  }

  public String getDescription() {
    return "Scan processing tool."
  }

  public String run(String[] args) {
    def cli = new CliBuilder(usage: "${getName()} <options> [-h]")  
    cli.h(longOpt:'help', argName:'usage information', required:false, 'show usage information') 
    cli.p(longOpt:'port', 'port', required:false, args:1)
    cli.r(longOpt:'run', argName:'begin process', required:true, 'begin processing') 
    cli.t(longOpt:'test', argName:'test', required:false, 'test single run only') 
    OptionAccessor opt = cli.parse(args); if(!opt) { return }  
    def config = YCOAConfiguration.getConfiguration()
    def resourceManager = new ResourceManager()
    resourceManager.extractResource("res/ycoa", new File("."))
    resourceManager.extractResource("webapps", new File("webapps"))
    def ycoaServletContainer = new YCOAServletContainer()
    def port = 80
    if(opt.p) port = Integer.parseInt(opt.p)
    log.debug("starting ScanTool")
    try {
      log.info("[${Archive.getUniqueTimeStamp()}]")
      def scanClient = new ScanClient("localhost", port)
      def result = null
      if(opt.t) {
        def scanController = ScanController.getInstance()
        log.debug(scanController.process())
      } else {
        try {
          result = scanClient.run()
          log.debug("RESULT: ${result}")
        } catch(e) {
          //e.printStackTrace()
          log.error("${e.getMessage()}")
          ycoaServletContainer.start(port)
          result = scanClient.run()
          log.error("RESULT: ${result}")
          ycoaServletContainer.join()
        }
      }
    } catch(Exception e) {
      //e.printStackTrace()
      log.error("${e.getMessage()}")
      ycoaServletContainer.stop()
    }
  }

}

// *EOF*
